package com.xuzhijie.pms.utils;

import cn.hutool.jwt.JWTUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xuzhijie.pms.common.Constants;
import com.xuzhijie.pms.exception.PmsServerException;

import java.util.Date;
import java.util.Map;

public class JwtUtils {

    private static final long EXPIRATION_TIME = 86400000;



    public static String generateToken(String userId, String sign){
        return JWT.create()
                .withSubject(userId)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(Algorithm.HMAC256(sign));
    }

    public static String getUserIdFromToken(String token) {

        String userId;
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            Map<String, Claim> claims = decodedJWT.getClaims();
            Claim userIdClaim = claims.get("sub");
            userId = userIdClaim.asString();
            System.out.println(userId);
        }catch (Exception e){
            throw new PmsServerException("token验证失败，请重新登陆", Constants.CODE_401);
            //e.printStackTrace();
        }
        return userId;
    }

    //验证token是否过期
    public static boolean validateToken(String token,String sign) {
        try {
            JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
            return true;
        } catch (Exception e) {
            throw new PmsServerException("登陆过期请重新登陆",Constants.CODE_401);
        }
    }
}
